package com.atguigu.ossservice.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.commonutils.utils.ConstantPropertiesUtil;
import com.atguigu.ossservice.service.FileService;
import com.atguigu.servicebase.handler.GuliException;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String uploadFileOss(MultipartFile file) {
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {
            //创建OSSclient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //uuid
            String uuid = UUID.randomUUID().toString();
            fileName = uuid+fileName;

            //定义文件目录
            String path = new DateTime().toString("yyyy/MM/dd");//2020/06/22
            fileName = path+"/"+fileName;
            ossClient.putObject(bucketName, fileName, inputStream);

            //关闭OSSClient
            ossClient.shutdown();
            //拼接url
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (IOException e) {
           throw new GuliException(20001,"上传失败");
        }
    }
}
